package cn.tedu.zhyl.system.service.impl;

import cn.tedu.zhyl.base.exception.ServiceException;
import cn.tedu.zhyl.base.help.TreeHelper;
import cn.tedu.zhyl.base.response.StatusCode;
import cn.tedu.zhyl.base.utils.AuthContext;
import cn.tedu.zhyl.system.mapper.SysMenuMapper;
import cn.tedu.zhyl.system.pojo.dto.SysMenuDTO;
import cn.tedu.zhyl.system.pojo.entity.SysMenu;
import cn.tedu.zhyl.system.pojo.vo.SysMenuVO;
import cn.tedu.zhyl.system.service.SysMenuService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysMenuServiceImpl implements SysMenuService {
    @Autowired
    private SysMenuMapper sysMenuMapper;
    @Override
    public List<SysMenuVO> getList() {
        List<SysMenuVO> menuList = sysMenuMapper.getList();
        return TreeHelper.buildTree(menuList,0);
    }

    @Override
    public void save(SysMenuDTO sysMenuDTO) {
        Integer id = sysMenuDTO.getId();
        SysMenu sysMenu = new SysMenu();
        BeanUtils.copyProperties(sysMenuDTO,sysMenu);
        if(id == null){
            sysMenu.setCreateBy(AuthContext.get().getId());
            sysMenuMapper.insert(sysMenu);
        }else {
            sysMenu.setUpdateBy(AuthContext.get().getId());
            sysMenuMapper.update(sysMenu);

        }
    }

    @Override
    public void deleteById(Integer id) {
        List<SysMenuVO> listByPid = sysMenuMapper.getListByPid(id);

        // 当删除父级菜单时要么递归删除，要么抛出错误不让删
        /*if (!listByPid.isEmpty()){
            listByPid.forEach(item->{
                deleteById(item.getId());
            });
        }*/
        if(!listByPid.isEmpty()){
            throw new ServiceException(StatusCode.REMOVE_MENU_ERROR);
        }

        sysMenuMapper.delete(id);
    }

    @Override
    public List<SysMenuVO> findMenusByPid(Integer pid) {
        return sysMenuMapper.getListByPid(pid);
    }
}
